//
//  SVQRcodeEditViewController.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/6/26.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVQRcodeEditViewController.h"
#import "SVNavigationBar.h"
#import "QRCodeUtil.h"
#import "SVConfig.h"
#import "SVQRCode.h"
#import "SVTextEditViewController.h"
#import "SVTextView.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "SVAPIReqeust.h"

@interface SVQRcodeEditViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate>{
    UITableView *contentTable;
    NSMutableArray *titles;
    NSMutableArray *placeHolders;
    NSMutableArray *values;
    UIImageView    *logo;
}

@end

@implementation SVQRcodeEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorMake(239, 239, 239, 1);
    // Do any additional setup after loading the view.
    SVNavigationBar *naviBar = [[SVNavigationBar alloc]init];
    [naviBar setQrcodeHandler:^{
        [QRCodeUtil pushQRCodeVC:self WithCompletionHandler:^(BOOL success, NSString *result) {
            
        }];
    }];
    [naviBar setBackHander:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [naviBar setTitle:@"二维码编辑"];
    naviBar.showBackButton = YES;
    naviBar.showShareButton = YES;
    [self.view addSubview:naviBar];
    
    titles = [NSMutableArray arrayWithArray:@[@[@"品牌"],@[@"标题",@"简介"]]];
    placeHolders = [NSMutableArray arrayWithArray:@[@[@"您的品牌"],@[@"二维码标题",@"二维码简介"]]];
    values = [NSMutableArray array];
    
    NSMutableArray *qrValues = [NSMutableArray arrayWithObjects:@"",@"", nil];
    if(self.qrcode.name && self.qrcode.name.length){
        [qrValues replaceObjectAtIndex:0 withObject:self.qrcode.name];
    }
    if(self.qrcode.des && self.qrcode.des.length){
        [qrValues replaceObjectAtIndex:1 withObject:self.qrcode.des];
    }
    
    NSMutableArray *brandValues = [NSMutableArray arrayWithObjects:@"", nil];
    if(self.qrcode.companyBrand && self.qrcode.companyBrand.length){
        [brandValues replaceObjectAtIndex:0 withObject:self.qrcode.companyBrand];
    }
    [values addObject:brandValues];
    [values addObject:qrValues];
    
    UIImageView *qrIcon = [[UIImageView alloc]initWithFrame:CGRectMake(S(90), CGRectGetMaxY(naviBar.frame)+S(16), S(140), S(140))];
    qrIcon.contentMode = UIViewContentModeScaleAspectFill;
    qrIcon.image = [UIImage imageNamed:@"qr_edit_icon"];
    [self.view addSubview:qrIcon];
    
    logo = [[UIImageView alloc]initWithFrame:CGRectMake(S(55), S(55), S(30), S(30))];
    logo.layer.cornerRadius = S(4);
    logo.layer.masksToBounds = YES;
    [qrIcon addSubview:logo];
    
    UIButton *addLogo = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMinX(qrIcon.frame), CGRectGetMaxY(qrIcon.frame)+S(8), S(140), S(30))];
    [addLogo setBackgroundImage:[UIImage imageNamed:@"icon_add_logo"] forState:UIControlStateNormal];
    [addLogo addTarget:self action:@selector(clickAddLogo:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addLogo];
    
    contentTable = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(addLogo.frame), __SCREEN_WIDTH__, __SCREEN_HEIGHT__-CGRectGetMaxY(addLogo.frame)-S(12)) style:UITableViewStyleGrouped];
    contentTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    contentTable.dataSource = self;
    contentTable.delegate = self;
    contentTable.scrollEnabled = NO;
    [self.view addSubview:contentTable];
    [contentTable reloadData];
    
    UIButton *saveButton = [[UIButton alloc]initWithFrame:CGRectMake(S(20), __SCREEN_HEIGHT__-S(52)-S(44), S(280), S(44))];
    saveButton.backgroundColor = UIColorMake(249, 80, 0, 1);
    saveButton.layer.cornerRadius = S(5);
    saveButton.layer.masksToBounds = YES;
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    saveButton.titleLabel.font = FontM(17);
    [saveButton addTarget:self action:@selector(clickSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
    
    UILabel *copyright = [[UILabel alloc]initWithFrame:CGRectMake(0, __SCREEN_HEIGHT__-S(7)-S(15), __SCREEN_WIDTH__, S(15))];
    copyright.textAlignment = NSTextAlignmentCenter;
    copyright.font = Font(12);
    copyright.textColor = UIColorMake(249, 74, 0, 1);
    copyright.text = @"copyright@ccinon";
    [self.view addSubview:copyright];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)clickAddLogo:(UIButton *)sender{
    UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
    photoPicker.delegate = self;
    photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    photoPicker.mediaTypes = @[(NSString *)kUTTypeImage];
    photoPicker.allowsEditing = YES;
    [self presentViewController:photoPicker animated:YES completion:nil];
}

- (void)clickSaveButton:(UIButton *)sender{
    if(self.state == SV_QRCODE_EDIT){
        [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/edt") method:@"POST" parametors:@{@"vod_qr_title":values[1][0],@"vod_qr_describe":values[1][1],@"vod_qr_brand":values[0][0],@"vod_qr_id":[NSString stringWithFormat:@"%ld",self.qrcode.ID]} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
            if(success){
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else{
        [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/use") method:@"POST" parametors:@{@"vod_qr_title":values[1][0],@"vod_qr_describe":values[1][1],@"vod_qr_brand":values[0][0],@"vod_qr_id":[NSString stringWithFormat:@"%ld",self.qrcode.ID]} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
            if(success){
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - table view delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionDatas = titles[section];
    return  sectionDatas.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return S(41);
    }else if(indexPath.section == 1){
        if(indexPath.row == 0){
            return S(41);
        }else{
            return S(100);
        }
    }
    return S(41);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return S(12);
    }else if(section == 1){
        return S(9);
    }else{
        return S(115);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = [NSString stringWithFormat:@"identifier%ld",indexPath.section];
    
    CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView *horline1 = [[UIView alloc]initWithFrame:CGRectMake(0, -1, __SCREEN_WIDTH__, 1)];
        horline1.backgroundColor = UIColorMake(191, 191, 191, 1);
        [cell addSubview:horline1];
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(S(13), S(12.5), S(37), S(16))];
        title.textColor = UIColorMake(160, 160, 160, 1);
        [title setFont:FontM(16)];
        title.tag = 1001;
        [cell addSubview:title];
        
        SVTextView *videoName = [[SVTextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(title.frame)+S(10), S(4), S(230), cellHeight-S(4))];
        videoName.textColor = UIColorMake(30, 30, 30, 1);
        [videoName setFont:Font(13)];
        videoName.tag = 1002;
        videoName.editable = NO;
        videoName.userInteractionEnabled = YES;
        [cell addSubview:videoName];
        
        UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(S(294), 0, S(11), S(18))];
        icon.image = [UIImage imageNamed:@"icon_arrow"];
        icon.center = CGPointMake(icon.center.x, cellHeight/2.0);
        [cell addSubview:icon];
        
        UIView *horline = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight-1, __SCREEN_WIDTH__, 1)];
        horline.backgroundColor = UIColorMake(191, 191, 191, 1);
        [cell addSubview:horline];
    }
    
    UILabel *title = [cell viewWithTag:1001];
    UITextView *placeHolder = [cell viewWithTag:1002];
    
    title.text = titles[indexPath.section][indexPath.row];
    placeHolder.text = placeHolders[indexPath.section][indexPath.row];
    
    NSString *value = values[indexPath.section][indexPath.row];
    if(value.length > 0){
        placeHolder.text = value;
        placeHolder.textColor = UIColorMake(30, 30, 30, 1);
    }else{
        placeHolder.textColor = UIColorMake(219, 219, 219, 1);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
    SVTextEditViewController *textEdit = [[SVTextEditViewController alloc]init];
    textEdit.text = values[indexPath.section][indexPath.row];
    [textEdit setDoneHandler:^(NSString *result){
        if(result.length > 0){
            NSArray *oldValues = values[indexPath.section];
            NSMutableArray *newValues = [NSMutableArray array];
            for (int i=0;i<oldValues.count;i++){
                if(i == indexPath.row){
                    [newValues addObject:result];
                }else{
                    [newValues addObject:oldValues[i]];
                }
            }
            [values replaceObjectAtIndex:indexPath.section withObject:newValues];
        }
        [contentTable reloadData];
    }];
    [self.navigationController pushViewController:textEdit animated:YES];
    
}

#pragma mark - UIImageViewController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeImage]){
        UIImage *image = [info objectForKey: UIImagePickerControllerEditedImage];
        logo.image = image;
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
